import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioClient {
    private static final String SERVER = "localhost";
    private static final int[] PORT_LIST = new int[]{8001, 8002, 8003, 8004, 8005, 8006, 8007, 8008, 8009, 8010};

    public static void main(String[] args) throws IOException {
        String messageBase = "hello, I'm client";
        for (int i = 0; i < PORT_LIST.length; i++) {
            new Thread(new ClientThread(SERVER, PORT_LIST[i], messageBase + (i + 1))).start();
        }
    }
}

/**
 * 客户端请求线程
 */
class ClientThread implements Runnable {
    private InetSocketAddress socketAddress;
    private String message;

    /**
     * @param host    服务器地址
     * @param port    服务器端口
     * @param message 发送消息内容
     */
    public ClientThread(String host, int port, String message) {
        this.socketAddress = new InetSocketAddress(host, port);
        this.message = message;
    }

    @Override
    public void run() {
        try {
            SocketChannel clntChan = SocketChannel.open(this.socketAddress);
            clntChan.configureBlocking(false);

            ByteBuffer byteBuffer = ByteBuffer.allocate(512);
            clntChan.write(ByteBuffer.wrap(this.message.getBytes())); // 向服务器发送数据

            while (true) {
                byteBuffer.clear();
                int readBytes = clntChan.read(byteBuffer); // 读取服务器端发送的数据
                if (readBytes > 0) {
                    byteBuffer.flip();
                    System.out.println("Client: data from server = " + new String(byteBuffer.array(), 0, readBytes));
                    clntChan.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
